//
//  BRScanViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/7.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRScanViewController.h"
#import "BRScanView.h"
#import "BRReportStillRunViewController.h"
#import "BRRentingViewController.h"
#import "BRScanModel.h"
#import "BRPaymentViewController.h"
#import "BRCanRentModel.h"
#import "BRRuleViewController.h"
#import "BRScanResultViewController.h"

@interface BRScanViewController ()<QMUITextFieldDelegate>

@property (nonatomic,strong) BRScanView *scanView;

@property (nonatomic,strong) BRScanModel *scaneInfoModel;

@property (nonatomic,strong) QMUITextField *textF;

@property (nonatomic,strong) NSString *sno;

@property (nonatomic,strong) QMUIButton *nextBtn;

@property (nonatomic,assign) BOOL isFirstIn;

@end

@implementation BRScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.sno = @"";
    [self setUI];
    self.isFirstIn = YES;
    WS(weakSelf);
    self.scanView.scanBlock = ^(NSArray * _Nonnull metadataObjects, NSString * _Nonnull lastUrlStr) {
        [weakSelf scanleNextDo:metadataObjects urlStr:lastUrlStr];
    };
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
//    [BRThemeManage br_isDarkStatusBar:NO];
    
    if (self.isFirstIn) {
        //第一次进来加快相机展示
        [GGPermissionsManage checkCameraPer:^{
            [self.scanView startAnimate];
            [self.scanView startRuning];
            
        } faile:^{
            
        }];
    }
    [BRUserManager share].isScanIn = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
//    [self toNext:@"1111"]; ///ceshi
    
    if (self.isFirstIn) {
        self.isFirstIn = NO;
        return;
    }
    [GGPermissionsManage checkCameraPer:^{
        [self.scanView startAnimate];
        [self.scanView startRuning];
        
    } faile:^{
        
    }];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.scanView stopRuning];
//    [BRThemeManage br_statusBarStyle];
}
#pragma mark - Net --
- (void)reqestRule:(NSString *)sno url:(NSString *)qrUrl {
    
    [BRHud showInView:self.view];

    NSString *urlStr = [BRAPI orderBilling];
   
    
    [[BRRequestManager shared] GET:urlStr params:@{@"sno":sno,@"qrUrl":qrUrl} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {

        self.scaneInfoModel = [BRScanModel  mj_objectWithKeyValues:dataDict[@"data"]];
        USERManager.ruleModel = self.scaneInfoModel.billing;
        [BRHud hiddenInView:self.view];
        self.nextBtn.enabled = YES;
        if (self.scaneInfoModel.code == 0) {
         
            /// 判断租借条件
            [self req_rentCheck:^{
                //跳转规则
                [self toNext:sno];
            } by:sno];
            
            return;
        }
        if (self.scaneInfoModel.code == 1) {
            // 低电量信息
            NSString *text = Localized(@"Scan_lowPower_notify");
           
            NSString *subtext = [NSString stringWithFormat:text,self.scaneInfoModel.maxBc];

            BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"Scan_lowPower") subTitle:subtext cancelAction:^{
                NSLog(@"取消");
                [self.scanView startRuning];
            } successAction:^{
                NSLog(@"确定");
               
                [self toNext:sno];
            } showBC:NO];

            [self.view addSubview:alertV];
            return;
        }

    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [self br_startRuning];
        self.nextBtn.enabled = YES;
        [BRHud hiddenInView:self.view];
    }];
}


- (void)toNext:(NSString *)sno {
    
    
    BRRuleViewController *vc = [[BRRuleViewController alloc] init];
    vc.sno  = sno;
    vc.dto = self.scaneInfoModel;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)req_rentCheck:(BRVoidBlock)allowSucc by:(NSString *)sno {
    [BRHud showInView:self.view];
    [[BRRequestManager shared] GET:[NSString stringWithFormat:@"%@?sno=%@",[BRAPI canRent],sno] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        [BRHud hiddenInView:self.view];
        BRCanRentModel *model = [BRCanRentModel mj_objectWithKeyValues:dataDict[@"data"]];
        
        /*
         0:可以租借 1：没有绑定银行卡 2：有未支付订单 3：子账号有未完成订单 4：租借订单已达上限 5：绑定的卡还有即将过期 6:主账号有未支付订单 7:主账号绑定的卡过期或异常状态 8：主账号绑定的卡即将过期 9:调查中的订单已达到上限
         */
        switch (model.rentOrNot) {
            case 0:{
                
                if (allowSucc) allowSucc();
                break;
            }
            case 1:{
//                [BRHud showAuto:Localized(@"Dialog_HomeRent_Message1") inView:self.view];
                if (allowSucc) allowSucc();
                break;
            }
//            case 1:{
//                
//                [self noBindCardAlert:model.requireRentalConfigs];
//                
//                break;
//            }
                
            case 2:{
                // 去支付 弹提示
                WS(weakSelf);
                BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"Public_notice") subTitle:Localized(@"Dialog_HomeRent_Message2") cancelStr:Localized(@"public_cancel") succStr:Localized(@"home_gotoPay") cancelAction:^{
                    
                } successAction:^{
//                    if (weakSelf.orderModel) {
//                        [weakSelf toPay];
//                    }
                    if (weakSelf.toPayBlock) {
                        weakSelf.toPayBlock();
                    }
                } showBC:YES];
                
                [self.view addSubview:alertV];
                
                break;
            }
            case 3:{
                //  子账号有未完成订单 弹提示
                [BRHud showAuto:Localized(@"Dialog_HomeRent_Message3") inView:self.view];
                break;
            }
//            case 9:
            case 4:{
                //  租借订单上限 弹提示 9为调查中
                [BRHud showAuto:Localized(@"Dialog_HomeRent_Message4") inView:self.view];
                break;
            }
            case 5:{
                // 绑定的卡即将过期 弹提示
                [BRHud showAuto:Localized(@"Dialog_HomeRent_Message7") inView:self.view];
                break;
            }
            case 6:{
                // 主账号有未支付订单 弹提示
                
                NSLog(@"主账号有未支付订单");
                [BRHud showAuto:Localized(@"Dialog_HomeRent_Message5") inView:self.view];
                break;
            }
            case 7:
                //  主账号绑定的卡过期或异常状态 弹提示
            case 8:{
                //主账号绑定的卡即将过期 弹提示
                [BRHud showAuto:Localized(@"Dialog_HomeRent_Message7") inView:self.view];
                break;
            }
            case 9:{
                //  租借订单上限 弹提示 9为调查中
                [BRHud showAuto:Localized(@"Dialog_HomeRent_Message9") inView:self.view];
                break;
            }
            default:
                break;
        }
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
        
    }];
    
    
}

- (void)noBindCardAlert:(NSArray *)requireRentalConfigs {
    
   
    NSInteger type = 1;
    
    [BRUserManager share].isScanIn = YES;
    if (self.bindBlock) self.bindBlock(type);
}

#pragma mark - Click --
- (void)nextClick:(QMUIButton *)btn {
    
    if (self.textF.text.length <= 0) {
        [BRHud showAuto:Localized(@"toast_validSN") inView:self.view];
        return;
    }
    [self.textF resignFirstResponder];
    btn.enabled = NO;
    self.sno = self.textF.text;

    // 直接跳转到扫码结果页，传入deviceId（sno）
    [self toScanResult:self.textF.text];
    btn.enabled = YES;
}

- (void)scanleNextDo:(NSArray * _Nonnull)metadataObjects urlStr:(NSString * _Nonnull)lastUrlStr {
    
    AVMetadataMachineReadableCodeObject * metadataObject = metadataObjects.firstObject;
    NSLog(@"%@", metadataObject.stringValue);
    NSString *str = metadataObject.stringValue;
    
    NSString *deviceId = nil;
    
    // https://links.youdianstar.com/MjBKRTAyOTQ
    if ([str containsString:@"https://links.youdianstar.com/"] && ![str containsString:@"?"]) {
        
        NSURL *url = [NSURL URLWithString:str];
        NSString *path = url.path;
        
        NSLog(@"%@",path);
        path = [path stringByReplacingOccurrencesOfString:@"/" withString:@""];
        NSLog(@"new = %@",path);
        if (path.length != 0) {
            // 从短链接中提取deviceId
            deviceId = path;
            [self toScanResult:deviceId];
            return;
        }
    }
    
    // @"http://shareasy.com.sg/app/device.html?sno=MA101707000007"
    NSRange range = [str rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        [self errorShow];
        return ;
    }
 
    NSMutableDictionary *scanDic = [MINUtils getURLParameters:str];
    
    if (BR_DictIsEmpty(scanDic)) {
        [self errorShow];
        return ;
    }
    
    NSArray *keys = [scanDic allKeys];
    
    if (![keys containsObject:@"id"] && ![keys containsObject:@"sno"] && ![keys containsObject:@"deviceId"]) {
        NSLog(@"3232");
        [self errorShow];
        return ;
    }
    
    // 优先使用 deviceId，如果没有则使用 id 或 sno
    if ([keys containsObject:@"deviceId"]) {
        deviceId = scanDic[@"deviceId"];
    } else if ([keys containsObject:@"id"]) {
        deviceId = scanDic[@"id"];
    } else if ([keys containsObject:@"sno"]) {
        deviceId = scanDic[@"sno"];
    }
    
    if (self.scanleStatus == SCANLE_DevNumber) {
        [self.navigationController popViewControllerAnimated:YES];
        //扫码返回number
        if (self.blockScanNum) {
            self.blockScanNum(deviceId, metadataObject.stringValue);
        }
        return;
    }
    
    if (deviceId && deviceId.length > 0) {
        [self toScanResult:deviceId];
    } else {
        [self errorShow];
    }
}

/// 跳转到扫码结果页
- (void)toScanResult:(NSString *)deviceId {
    BRScanResultViewController *vc = [[BRScanResultViewController alloc] init];
    vc.deviceId = deviceId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 允许删除操作
    if ([string isEqualToString:@""]) {
        return YES;
    }
    
    // 限制最大长度为30（设备ID可能较长）
    NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (newText.length > 30) {
        return NO;
    }
    
    // 允许输入字母、数字和常见字符（用于设备ID）
    // 设备ID通常包含字母、数字，可能还包含连字符、下划线等
    NSCharacterSet *allowedCharacters = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"];
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:string];
    
    if ([allowedCharacters isSupersetOfSet:characterSet]) {
        return YES;
    }
    
    return NO;
}

- (void)errorShow {
    [BRHud showAuto:Localized(@"toast_validQRCode") inView:self.view];
    [self br_startRuning];
}

- (void)br_startRuning {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.scanView startRuning];
    });
}


#pragma mark - Set UI --
- (void)setUI {
    
    [self createTop:@"" imageStr:@"arrow_left_white44"];

    
    [self.view insertSubview:self.scanView atIndex:0];
    [self.scanView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    
    if (self.scanleStatus == SCANLE_DevNumber) return;
    /// 265 / 2.0 + 20
    CGFloat topY = 265 / 2.0 + 20;
    CGFloat X =(kScreenWidth - 265) / 2.0;
    QMUITextField *stationTF = [[QMUITextField alloc] init];
    stationTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    stationTF.clearButtonPositionAdjustment = UIOffsetMake(-14, 0);
    stationTF.textInsets = UIEdgeInsetsMake(0, 16, 0, 16);
    stationTF.placeholder = Localized(@"home_enterStationID");
    stationTF.placeholderColor = UIColorWhite;
    stationTF.font = [UIFont fontM:14];
    stationTF.textColor = UIColorWhite;
    stationTF.delegate = self;
    stationTF.tintColor = kColorMain;
    stationTF.userInteractionEnabled = YES; // 确保可以交互
    stationTF.enabled = YES; // 确保启用
    stationTF.keyboardType = UIKeyboardTypeDefault; // 允许输入数字和字母
    stationTF.autocorrectionType = UITextAutocorrectionTypeNo; // 关闭自动纠错
    stationTF.autocapitalizationType = UITextAutocapitalizationTypeNone; // 关闭自动大写
    [self.view addSubview:stationTF];
    stationTF.layer.cornerRadius = 5;
    stationTF.backgroundColor = UIColorMakeWithRGBA(255, 255, 255, 0.4);
    [stationTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(265 - 52);
        make.height.mas_equalTo(44);
        make.left.offset(X);
        make.bottom.equalTo(self.view.mas_centerY).offset(-topY);
    }];
    stationTF.adjustsFontSizeToFitWidth = YES;
    stationTF.minimumFontSize = 8;
//    stationTF.text = @"10000119";
    self.textF = stationTF;
    
    QMUIButton *nextBtn = [[QMUIButton alloc] init];
    [nextBtn setImage:UIImageMake(@"scan_next") forState:UIControlStateNormal];
    [self.view addSubview:nextBtn];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(stationTF);
        make.left.equalTo(stationTF.mas_right).offset(8);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(44);
    }];
    [nextBtn addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchUpInside];
    self.nextBtn = nextBtn;
    
}

#pragma mark - Lazy load --
- (BRScanView *)scanView {
    if (_scanView == nil) {
        _scanView = [[BRScanView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) needDown:self.swapState == 1];
    }
    return _scanView;
}


//- (BOOL)preferredNavigationBarHidden {
//    return YES;
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
